package nautilus.moneykeeper.adapter;

import java.util.ArrayList;
import java.util.List;

import nautilus.moneykeeper.R;
import nautilus.moneykeeper.dto.Account;
import nautilus.moneykeeper.dto.CurrencyUnit;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListAccountAdapter extends BaseAdapter{
	private final Context _context;
	private final ArrayList<Account> _accounts = new ArrayList<Account>();
	
	private static final int[] bgColors = new int[] { 0xbcedab, 0xf2e9d5 };
	
	private LayoutInflater _inflater;
	
	public ListAccountAdapter(Context context, List<Account> accounts){		
		_context = context;
		_accounts.addAll(accounts);
		_inflater =  (LayoutInflater)_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	@Override
	public int getCount() {
		return _accounts.size();
	}

	@Override
	public Object getItem(int index) {
		return _accounts.get(index);
	}

	@Override
	public long getItemId(int index) {
		return _accounts.get(index).getId();
	}

	
	public void refresh(ArrayList<Account> accs){
		_accounts.clear();
		_accounts.addAll(accs);
		notifyDataSetChanged();
	}
	
	@Override
	public View getView(int pos, View convertView, ViewGroup parent){
		View rowView = convertView;
		RowItemView itemView;
		
		if(rowView == null){
			//get an instance of row layout item			
			rowView = _inflater.inflate(R.layout.list_account_item, null);
	
			itemView = new RowItemView();
			itemView.tvName = (TextView)rowView.findViewById(R.id.list_account_item_name);
			itemView.tvBanlance = (TextView)rowView.findViewById(R.id.list_account_item_balance);
			itemView.tvType = (TextView)rowView.findViewById(R.id.list_account_type);
			
			rowView.setTag(itemView);
		}else{
			itemView = (RowItemView)(rowView.getTag());
		}
		
		Account acc = _accounts.get(pos);
		itemView.tvName.setText(acc.getName());
		getBalanceText(itemView.tvBanlance, acc.getBalance(), acc.getCurrencyUnit());
		//Log.i("ListAccountAdapter", String.format("%s %s %s", itemView.tvType, acc.getType(), acc.getType().getName()));
		itemView.tvType.setText(acc.getType().getName());
		
		int icolor = pos % bgColors.length;
		rowView.setBackgroundColor(bgColors[icolor]);
		
		return rowView;
	}
	
	protected static class RowItemView{
		protected TextView tvName, tvBanlance, tvType;
	}
	
	private void getBalanceText(TextView tv, long balance, CurrencyUnit unit){
		String text = "Balance: <font color='#ff0404'><b>" + balance + "</b></font> " + unit.getName();  
		tv.setText(Html.fromHtml(text));
	}
}
